import {join} from 'path';
import {
    AutoBackupConfig,
    CacheConfig,
    DirectoryTreeNode,
    FileHistory,
    FileIndexItem,
    FileSpaceConfig,
    IEncryption,
    OpenedDirectoryCache,
    OpenedFileRecord,
    OperationResult,
    RecoveryPoint,
    TempFileInfo,
    TreeWalkCallback,
    TreeWalkOptions
} from '../types';
import {FileUtil} from '../utils/fileUtil';
import {CacheManager} from '../utils/cacheManager';
import {BackupManager} from '../utils/backupManager';
import {TempFileManager} from '../utils/tempFileManager';

/**
 * 文件空间管理器
 */
export class FileSpace {
    /** 文件空间配置 */
    private config: FileSpaceConfig;
    /** 加密器实例 */
    private encryption?: IEncryption;
    /** 索引文件路径 */
    private indexPath: string;
    /** 历史记录目录路径 */
    private historyPath: string;
    /** 文件内容缓存管理器 */
    private contentCache: CacheManager<string>;
    /** 文件索引缓存管理器 */
    private indexCache: CacheManager<FileIndexItem[]>;
    /** 目录树缓存管理器 */
    private treeCache: CacheManager<DirectoryTreeNode>;
    /** 备份管理器 */
    private backupManager: BackupManager;
    /** 临时文件管理器 */
    private tempManager: TempFileManager;
    /** 文件索引键 */
    private FILE_INDEX_KEY = 'fileIndex';
    /** 打开记录文件路径 */
    private openedFilesPath: string;
    /** 打开记录缓存 */
    private openedFilesCache: Map<string, OpenedFileRecord>;
    /** 打开的目录缓存 */
    private openedDirectoryCache: Map<string, OpenedDirectoryCache>;
    /** 目录缓存过期时间（毫秒） */
    private readonly DIRECTORY_CACHE_TTL = 5 * 60 * 1000; // 5分钟

    /**
     * 构造函数
     * @param config 文件空间配置
     */
    constructor(config: FileSpaceConfig) {
        this.config = config;
        this.encryption = config.encryption;
        this.indexPath = join(config.rootPath, '.index.json');
        this.historyPath = join(config.rootPath, '.history');
        this.openedFilesPath = join(config.rootPath, '.opened-files.json');
        this.openedFilesCache = new Map();
        this.openedDirectoryCache = new Map();

        // 初始化缓存管理器
        const cacheConfig: CacheConfig = {
            enabled: true,
            ttl: 5 * 60 * 1000, // 5分钟
            maxEntries: 1000,
            maxItemSize: 10 * 1024 * 1024 // 10MB
        };

        this.contentCache = new CacheManager<string>(cacheConfig);
        this.indexCache = new CacheManager<FileIndexItem[]>({
            ...cacheConfig,
            ttl: 30 * 1000 // 索引缓存时间较短
        });
        this.treeCache = new CacheManager<DirectoryTreeNode>({
            ...cacheConfig,
            maxEntries: 100
        });

        // 初始化备份管理器
        const backupConfig: AutoBackupConfig = {
            enabled: true,
            interval: 5 * 60 * 1000, // 5分钟
            maxBackups: 50,
            retentionTime: 7 * 24 * 60 * 60 * 1000, // 7天
            maxBackupSize: 100 * 1024 * 1024 // 100MB
        };

        this.backupManager = new BackupManager(config.rootPath, backupConfig);
        this.backupManager.onRestore = this.restoreFromBackup.bind(this);

        // 初始化临时文件管理器
        this.tempManager = new TempFileManager({
            tempDir: join(config.rootPath, '.temp'),
            expireTime: 24 * 60 * 60 * 1000  // 默认24小时
        });
    }

    /**
     * 初始化文件空间
     */
    async initialize(): Promise<void> {
        // 创建必要的目录
        await FileUtil.createDirectory(this.config.rootPath);
        await FileUtil.createDirectory(this.historyPath);

        // 初始化索引文件
        if (!await FileUtil.exists(this.indexPath)) {
            const rootDir = this.buildRootDirectory()
            await FileUtil.writeFile(this.indexPath, JSON.stringify([rootDir.item]));
        }

        // 初始化打开记录文件
        if (!await FileUtil.exists(this.openedFilesPath)) {
            await FileUtil.writeFile(this.openedFilesPath, JSON.stringify([]));
        } else {
            // 加载打开记录
            await this.loadOpenedFiles();
        }

        // 初始化备份管理器
        await this.backupManager.initialize();

        // 初始化临时文件管理器
        await this.tempManager.initialize();

        // 检查是否有未完成的备份需要恢复
        await this.checkForRecovery();
    }

    /**
     * 加载打开记录
     */
    private async loadOpenedFiles(): Promise<void> {
        try {
            const content = await FileUtil.readFile(this.openedFilesPath);
            const records: OpenedFileRecord[] = JSON.parse(content);
            this.openedFilesCache.clear();
            for (const record of records) {
                this.openedFilesCache.set(record.fileId, record);
            }
        } catch (error) {
            console.error('加载打开记录失败:', error);
            // 如果加载失败，初始化为空记录
            this.openedFilesCache.clear();
        }
    }

    /**
     * 保存打开记录
     */
    private async saveOpenedFiles(): Promise<void> {
        try {
            const records = Array.from(this.openedFilesCache.values());
            await FileUtil.writeFile(this.openedFilesPath, JSON.stringify(records, null, 2));
        } catch (error) {
            console.error('保存打开记录失败:', error);
        }
    }

    /**
     * 获取文件索引列表
     */
    async getFileIndex(): Promise<FileIndexItem[]> {
        // 尝试从缓存获取
        const cachedIndex = this.indexCache.get(this.FILE_INDEX_KEY);
        if (cachedIndex) {
            return cachedIndex;
        }

        const content = await FileUtil.readFile(this.indexPath);
        const index = JSON.parse(content);

        // 存入缓存
        this.indexCache.set(this.FILE_INDEX_KEY, index, content.length);

        return index;
    }

    /**
     * 获取文件内容
     * @param fileId 文件ID
     */
    async getFileContent(fileId: string): Promise<OperationResult<string>> {
        try {
            // 先从缓存获取
            const cached = this.contentCache.get(fileId);
            if (cached) {
                return { success: true, data: cached };
            }

            const index = await this.getFileIndex();
            const file = index.find(item => item.id === fileId);

            if (!file) {
                return { success: false, error: '文件不存在' };
            }

            if (file.isDirectory) {
                return { success: false, error: '不能获取目录的内容' };
            }

            const filePath = join(this.config.rootPath, file.relativePath);
            let content = await FileUtil.readFile(filePath);

            if (this.encryption) {
                content = await this.encryption.decrypt(content);
            }

            // 缓存内容
            this.contentCache.set(fileId, content, content.length);

            return { success: true, data: content };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 保存文件内容
     * @param fileId 文件ID
     * @param content 文件内容
     */
    async saveFileContent(fileId: string, content: string): Promise<OperationResult<void>> {
        try {
            const index = await this.getFileIndex();
            const file = index.find(item => item.id === fileId);

            if (!file) {
                return { success: false, error: '文件不存在' };
            }

            // 先记录变更到备份管理器
            await this.backupManager.recordChange(fileId, content);

            const filePath = join(this.config.rootPath, file.relativePath);
            let saveContent = content;

            if (this.encryption && !file.isDirectory) {
                saveContent = await this.encryption.encrypt(content);
            }

            await FileUtil.writeFile(filePath, saveContent);
            await this.saveFileHistory(fileId, content);

            // 清除缓存
            this.contentCache.delete(fileId);

            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 保存文件历史记录
     * @param fileId 文件ID
     * @param content 文件内容
     */
    private async saveFileHistory(fileId: string, content: string): Promise<void> {
        const historyFile = join(this.historyPath, `${fileId}.json`);
        let histories: FileHistory[] = [];

        if (await FileUtil.exists(historyFile)) {
            const historyContent = await FileUtil.readFile(historyFile);
            histories = JSON.parse(historyContent);
        }

        histories.push({
            id: Date.now().toString(),
            fileId,
            content,
            version: histories.length + 1,
            createTime: Date.now(),
            updateTime: Date.now()
        });

        // 限制历史记录数量
        if (histories.length > this.config.maxHistoryCount) {
            histories = histories.slice(-this.config.maxHistoryCount);
        }

        await FileUtil.writeFile(historyFile, JSON.stringify(histories));
    }

    /**
     * 获取文件历史记录
     * @param fileId 文件ID
     */
    async getFileHistory(fileId: string): Promise<OperationResult<FileHistory[]>> {
        try {
            const historyFile = join(this.historyPath, `${fileId}.json`);

            if (!await FileUtil.exists(historyFile)) {
                return { success: true, data: [] };
            }

            const content = await FileUtil.readFile(historyFile);
            return { success: true, data: JSON.parse(content) };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 从备份恢复文件内容
     * @param fileId 文件ID
     * @param content 文件内容
     */
    private async restoreFromBackup(fileId: string, content: string): Promise<void> {
        await this.saveFileContent(fileId, content);
    }

    /**
     * 检查是否需要恢复
     */
    private async checkForRecovery(): Promise<void> {
        try {
            const points = await this.backupManager.getRecoveryPoints();
            if (points.length === 0) {
                return;
            }

            // 获取最新的恢复点
            const latestPoint = points[points.length - 1];
            const timeSinceLastPoint = Date.now() - latestPoint.createTime;

            // 如果最后一个恢复点是在1小时内创建的，可能是由于异常关机导致的
            if (timeSinceLastPoint < 60 * 60 * 1000) {
                await this.backupManager.restoreFromPoint(latestPoint.id);
            }
        } catch (error) {
            console.error('检查恢复点失败:', error);
        }
    }

    /**
     * 创建恢复点
     * @param description 恢复点描述
     */
    async createRecoveryPoint(description: string): Promise<OperationResult<RecoveryPoint>> {
        try {
            const point = await this.backupManager.createRecoveryPoint(description);
            return { success: true, data: point };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 从恢复点恢复
     * @param recoveryPointId 恢复点ID
     */
    async restoreFromRecoveryPoint(recoveryPointId: string): Promise<OperationResult<void>> {
        try {
            const success = await this.backupManager.restoreFromPoint(recoveryPointId);
            if (!success) {
                return { success: false, error: '恢复点不存在或已失效' };
            }
            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 创建文件
     * @param name 文件名称
     * @param content 文件内容（可选）
     * @param parentId 父目录ID（可选，不提供则创建在根目录）
     */
    async createFile(name: string, content: string = '', parentId?: string): Promise<OperationResult<FileIndexItem>> {
        try {
            // 获取父目录路径
            let parentPath = this.config.rootPath;
            let parentVPath = '';
            if (parentId) {
                const index = await this.getFileIndex();
                const parent = index.find(item => item.id === parentId);
                if (!parent) {
                    return { success: false, error: '父目录不存在' };
                }
                if (!parent.isDirectory) {
                    return { success: false, error: '父ID不是目录' };
                }
                parentPath = join(this.config.rootPath, parent.relativePath);
                parentVPath = parent.vRelativePath;
            }

            // 检查文件名是否合法
            if (!name || /[<>:"/\\|?*]/.test(name)) {
                return { success: false, error: '文件名不合法' };
            }

            // 创建文件并获取索引项
            let saveContent = content;
            if (this.encryption) {
                saveContent = await this.encryption.encrypt(content);
            }

            const { indexItem } = await FileUtil.createFileWithIndex(
                this.config.rootPath,
                parentPath,
                parentVPath,
                name,
                saveContent
            );

            // 更新索引
            const index = await this.getFileIndex();
            index.push(indexItem);
            await FileUtil.writeFile(this.indexPath, JSON.stringify(index));

            // 清除缓存
            this.indexCache.delete(this.FILE_INDEX_KEY);

            return { success: true, data: indexItem };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 创建目录
     * @param name 目录名称
     * @param parentId 父目录ID（可选，不提供则创建在根目录）
     */
    async createDirectory(name: string, parentId?: string): Promise<OperationResult<FileIndexItem>> {
        try {
            const index = await this.getFileIndex();
            let parentPath = this.config.rootPath;
            let parentVPath = '';
            if (parentId) {
                const parent = index.find(item => item.id === parentId);
                if (!parent) {
                    return { success: false, error: '父目录不存在' };
                }
                parentPath = join(this.config.rootPath, parent.relativePath);
                parentVPath = parent.vRelativePath;
            }

            // 检查目录深度
            if (parentVPath.split(FileUtil.separator).length >= this.config.maxDepth) {
                return { success: false, error: '超出最大目录深度限制' };
            }

            // 创建目录并获取索引项
            const { path, indexItem } = await FileUtil.createDirectoryWithIndex(
                this.config.rootPath,
                parentPath,
                parentVPath,
                name
            );

            index.push(indexItem);
            await FileUtil.writeFile(this.indexPath, JSON.stringify(index));

            // 清除缓存
            this.indexCache.delete(this.FILE_INDEX_KEY);

            return { success: true, data: indexItem };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 删除文件或目录
     * @param fileId 文件或目录ID
     */
    async delete(fileId: string): Promise<OperationResult<void>> {
        try {
            const index = await this.getFileIndex();
            const file = index.find(item => item.id === fileId);

            if (!file) {
                return { success: false, error: '文件不存在' };
            }

            const fullPath = join(this.config.rootPath, file.relativePath);
            await FileUtil.delete(fullPath);

            // 如果是目录，需要删除所有子项
            if (file.isDirectory) {
                const removeIds = index
                    .filter(item => item.relativePath.startsWith(file.relativePath))
                    .map(item => item.id);
                index.splice(0, index.length, ...index.filter(item => !removeIds.includes(item.id)));
            } else {
                index.splice(index.findIndex(item => item.id === fileId), 1);
            }

            await FileUtil.writeFile(this.indexPath, JSON.stringify(index));

            // 清除缓存
            this.indexCache.delete(this.FILE_INDEX_KEY);
            this.contentCache.delete(fileId);

            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 移动文件或目录
     * @param fileId 文件或目录ID
     * @param targetParentId 目标父目录ID（undefined表示移动到根目录）
     */
    async move(fileId: string, targetParentId: string | undefined): Promise<OperationResult<void>> {
        try {
            const index = await this.getFileIndex();
            const file = index.find(item => item.id === fileId);
            const targetParent = targetParentId
                ? index.find(item => item.id === targetParentId)
                : undefined;

            if (!file) {
                return { success: false, error: '文件不存在' };
            }

            if (targetParentId && !targetParent) {
                return { success: false, error: '目标目录不存在' };
            }

            const oldPath = join(this.config.rootPath, file.relativePath);
            const newRelativePath = targetParent
                ? join(targetParent.relativePath, file.id + (file.extension ? '.' + file.extension : ''))
                : file.id + (file.extension ? '.' + file.extension : '');
            const newPath = join(this.config.rootPath, newRelativePath);

            // 更新虚拟路径
            const newVRelativePath = targetParent
                ? join(targetParent.vRelativePath, file.title)
                : file.title;

            // 检查新路径的目录深度
            const depth = newVRelativePath.split(FileUtil.separator).length;
            if (depth > this.config.maxDepth) {
                return { success: false, error: '移动后将超出最大目录深度限制' };
            }

            await FileUtil.move(oldPath, newPath);

            // 更新索引中的路径
            const updatePaths = (oldPrefix: string, newPrefix: string, oldVPrefix: string, newVPrefix: string) => {
                for (const item of index) {
                    if (item.relativePath.startsWith(oldPrefix)) {
                        const relativeSuffix = item.relativePath.slice(oldPrefix.length);
                        const vRelativeSuffix = item.vRelativePath.slice(oldVPrefix.length);
                        item.relativePath = join(newPrefix, relativeSuffix);
                        item.vRelativePath = join(newVPrefix, vRelativeSuffix);
                    }
                }
            };

            updatePaths(file.relativePath, newRelativePath, file.vRelativePath, newVRelativePath);
            await FileUtil.writeFile(this.indexPath, JSON.stringify(index));

            // 清除缓存
            this.indexCache.delete(this.FILE_INDEX_KEY);
            this.contentCache.delete(fileId);

            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 复制文件或目录
     * @param fileId 文件或目录ID
     * @param targetParentId 目标父目录ID（undefined表示复制到根目录）
     * @param newName 新名称（可选）
     */
    async copy(fileId: string, targetParentId: string | undefined, newName?: string): Promise<OperationResult<FileIndexItem>> {
        try {
            const index = await this.getFileIndex();
            const file = index.find(item => item.id === fileId);
            const targetParent = targetParentId
                ? index.find(item => item.id === targetParentId)
                : undefined;

            if (!file) {
                return { success: false, error: '文件不存在' };
            }

            if (targetParentId && !targetParent) {
                return { success: false, error: '目标目录不存在' };
            }

            const sourcePath = join(this.config.rootPath, file.relativePath);
            const newTitle = newName || file.title;

            // 创建临时路径用于复制
            const tempPath = join(
                this.config.rootPath,
                targetParent ? targetParent.relativePath : '',
                newTitle
            );

            await FileUtil.copy(sourcePath, tempPath);

            // 获取新文件信息
            const newFileInfo = await FileUtil.getFileInfo(tempPath, this.config.rootPath);

            // 使用新ID重命名
            const finalPath = join(
                this.config.rootPath,
                targetParent ? targetParent.relativePath : '',
                newFileInfo.id + (newFileInfo.extension ? '.' + newFileInfo.extension : '')
            );
            await FileUtil.move(tempPath, finalPath);

            // 检查新路径的目录深度
            const depth = newFileInfo.vRelativePath.split(FileUtil.separator).length;
            if (depth > this.config.maxDepth) {
                await FileUtil.delete(finalPath);
                return { success: false, error: '复制后将超出最大目录深度限制' };
            }

            // 更新索引
            index.push(newFileInfo);

            if (file.isDirectory) {
                const subItems = await FileUtil.listDirectory(sourcePath, true);
                for (const subItem of subItems) {
                    const subSourcePath = join(sourcePath, subItem);
                    const subTempPath = join(tempPath, subItem);
                    const subFileInfo = await FileUtil.getFileInfo(subTempPath, this.config.rootPath);

                    // 使用新ID重命名子项
                    const subFinalPath = join(
                        finalPath,
                        subFileInfo.id + (subFileInfo.extension ? '.' + subFileInfo.extension : '')
                    );
                    await FileUtil.move(subTempPath, subFinalPath);

                    index.push(subFileInfo);
                }
            }

            await FileUtil.writeFile(this.indexPath, JSON.stringify(index));

            // 清除缓存
            this.indexCache.delete(this.FILE_INDEX_KEY);

            return { success: true, data: newFileInfo };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 获取目录内容
     * @param directoryId 目录ID（undefined表示根目录）
     */
    async getDirectoryContents(directoryId?: string): Promise<OperationResult<FileIndexItem[]>> {
        try {
            const index = await this.getFileIndex();
            const directory = directoryId
                ? index.find(item => item.id === directoryId)
                : undefined;

            if (directoryId && !directory) {
                return { success: false, error: '目录不存在' };
            }

            const dirPath = directory?.relativePath || '';
            const contents = index.filter(item => {
                const itemDir = item.relativePath.split(FileUtil.separator).slice(0, -1).join(FileUtil.separator);
                return itemDir === dirPath;
            });

            return { success: true, data: contents };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 构建根目录
     */
    public buildRootDirectory(): DirectoryTreeNode {
        return {
            id: 'root',
            item: {
                id: 'root',
                title: '根目录',
                extension: '',
                relativePath: '',
                vRelativePath: '',
                isDirectory: true,
                size: 0,
                createTime: Date.now(),
                updateTime: Date.now()
            },
            children: [],
            expanded: true,
            level: 0
        }
    }

    /**
     * 构建目录树
     * @param startPath 起始路径（相对于文件空间根目录）
     * @param options 遍历选项
     */
    async buildDirectoryTree(startPath = '', options: TreeWalkOptions = {}): Promise<OperationResult<DirectoryTreeNode>> {
        try {
            // 生成缓存键
            const cacheKey = `tree:${startPath}:${JSON.stringify(options)}`;

            // 尝试从缓存获取
            const cachedTree = this.treeCache.get(cacheKey);
            if (cachedTree) {
                return { success: true, data: cachedTree };
            }

            const index = await this.getFileIndex();
            const items = index.filter(item => {
                // 过滤起始路径下的项目
                if (!item.relativePath.startsWith(startPath)) {
                    return false;
                }

                // 如果设置了startFromPath，则只包含startPath本身和其直接子项
                if (options.startFromPath && startPath !== '') {
                    if (item.relativePath === startPath) {
                        return true;  // 包含目录本身
                    }
                    // 计算相对于startPath的路径部分
                    const relativeToStart = item.relativePath.substring(startPath.length);
                    if (relativeToStart.startsWith(FileUtil.separator)) {
                        // 去掉开头的分隔符
                        const pathParts = relativeToStart.substring(1).split(FileUtil.separator);
                        // 只返回直接子项（路径部分只有一段）
                        return pathParts.length === 1;
                    }
                    return false;
                }

                // 应用自定义过滤器
                if (options.filter && !options.filter(item)) {
                    return false;
                }

                // 处理文件包含选项
                if (!options.includeFiles && !item.isDirectory) {
                    return false;
                }

                return true;
            });

            // 按路径排序，确保父目录在前
            items.sort((a, b) => {
                const depthA = a.relativePath.split(FileUtil.separator).length;
                const depthB = b.relativePath.split(FileUtil.separator).length;
                if (depthA !== depthB) return depthA - depthB;
                return a.relativePath.localeCompare(b.relativePath);
            });

            // 如果设置了startFromPath，找到起始目录项
            let startItem: FileIndexItem | undefined;
            if (options.startFromPath && startPath) {
                startItem = items.find(item => item.relativePath === startPath);
                if (!startItem) {
                    return { success: false, error: '目录不存在' };
                }
            } else {
                // 如果没有设置startFromPath，确保根目录存在
                if (!items.find(item => item.relativePath === '')) {
                    return {success: false, error: '根目录不存在'};
                }
            }

            // 创建根节点
            const root: DirectoryTreeNode = {
                id: startItem!.id,
                item: startItem!,
                children: [],
                expanded: false,
                level: 0
            }

            const nodeMap = new Map<string, DirectoryTreeNode>([[startItem!.relativePath, root]]);

            for (const item of items) {
                // 如果是起始项，跳过（因为已经作为根节点）
                if (options.startFromPath && item === startItem) {
                    continue;
                }

                const pathParts = item.relativePath.split(FileUtil.separator);
                const itemName = pathParts.pop() || '';
                const parentPath = pathParts.slice(0, pathParts.length).join(FileUtil.separator);
                const level = pathParts.length + 1;

                // 检查最大深度限制
                if (options.maxDepth !== undefined && options.maxDepth >= 0 && level > options.maxDepth) {
                    continue;
                }

                // 创建当前节点
                const node: DirectoryTreeNode = {
                    id: item.id,
                    item,
                    children: [],
                    expanded: this.isFileOpened(item.id),
                    level
                };

                // 添加到父节点
                const parentNode = nodeMap.get(parentPath);
                if (parentNode) {
                    parentNode.children?.push(node);
                }

                // 如果是目录，添加到映射表
                if (item.isDirectory) {
                    nodeMap.set(item.relativePath, node);
                }
            }

            // 存入缓存（使用JSON.stringify估算大小）
            const treeJson = JSON.stringify(root);
            this.treeCache.set(cacheKey, root, treeJson.length);

            return { success: true, data: root };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 搜索目录树
     * @param searchPattern 搜索模式（支持简单的通配符 * 和 ?）
     * @param options 遍历选项
     */
    async searchDirectoryTree(searchPattern: string, options: TreeWalkOptions = {}): Promise<OperationResult<DirectoryTreeNode[]>> {
        try {
            const results: DirectoryTreeNode[] = [];
            const pattern = new RegExp('^' + searchPattern.replace(/\*/g, '.*').replace(/\?/g, '.') + '$');

            await this.walkDirectoryTree(
                (node) => {
                    if (pattern.test(node.item.title)) {
                        results.push(node);
                    }
                },
                '',
                { ...options, recursive: true }
            );

            return { success: true, data: results };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 获取目录树统计信息
     * @param directoryId 目录ID（undefined表示根目录）
     */
    async getDirectoryStats(directoryId?: string): Promise<OperationResult<{
        totalFiles: number;
        totalDirectories: number;
        totalSize: number;
        maxDepth: number;
    }>> {
        try {
            const stats = {
                totalFiles: 0,
                totalDirectories: 0,
                totalSize: 0,
                maxDepth: 0
            };

            const directory = directoryId
                ? (await this.getFileIndex()).find(item => item.id === directoryId)
                : undefined;

            await this.walkDirectoryTree(
                (node) => {
                    if (node.item.isDirectory) {
                        stats.totalDirectories++;
                    } else {
                        stats.totalFiles++;
                        stats.totalSize += node.item.size;
                    }
                    stats.maxDepth = Math.max(stats.maxDepth, node.level);
                },
                directory?.relativePath || '',
                { includeFiles: true, recursive: true }
            );

            return { success: true, data: stats };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 清除缓存
     */
    clearCache(): void {
        this.contentCache.clear();
        this.indexCache.clear();
        this.treeCache.clear();
    }

    /**
     * 获取缓存统计信息
     */
    getCacheStats(): {
        content: ReturnType<CacheManager<string>['getStats']>;
        index: ReturnType<CacheManager<FileIndexItem[]>['getStats']>;
        tree: ReturnType<CacheManager<DirectoryTreeNode>['getStats']>;
    } {
        return {
            content: this.contentCache.getStats(),
            index: this.indexCache.getStats(),
            tree: this.treeCache.getStats()
        };
    }

    /**
     * 创建临时文件
     * @param targetName 目标文件名
     * @param content 初始内容（可选）
     * @param parentId 父目录ID（可选）
     */
    async createTempFile(targetName: string, content: string = '', parentId?: string): Promise<OperationResult<TempFileInfo>> {
        try {
            // 检查文件名是否合法
            if (!targetName || /[<>:"/\\|?*]/.test(targetName)) {
                return { success: false, error: '文件名不合法' };
            }

            // 检查父目录是否存在
            if (parentId) {
                const index = await this.getFileIndex();
                const parent = index.find(item => item.id === parentId);
                if (!parent) {
                    return { success: false, error: '父目录不存在' };
                }
                if (!parent.isDirectory) {
                    return { success: false, error: '父ID不是目录' };
                }
            }

            const tempInfo = await this.tempManager.createTemp(targetName, parentId, content);
            return { success: true, data: tempInfo };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 更新临时文件内容
     * @param tempId 临时文件ID
     * @param content 新内容
     */
    async updateTempFile(tempId: string, content: string): Promise<OperationResult<void>> {
        try {
            const success = await this.tempManager.updateTemp(tempId, content);
            if (!success) {
                return { success: false, error: '临时文件不存在' };
            }
            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 获取临时文件内容
     * @param tempId 临时文件ID
     */
    async getTempFileContent(tempId: string): Promise<OperationResult<string>> {
        try {
            const content = await this.tempManager.getTempContent(tempId);
            if (content === null) {
                return { success: false, error: '临时文件不存在或已过期' };
            }
            return { success: true, data: content };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 删除临时文件
     * @param tempId 临时文件ID
     */
    async deleteTempFile(tempId: string): Promise<OperationResult<void>> {
        try {
            const success = await this.tempManager.deleteTemp(tempId);
            if (!success) {
                return { success: false, error: '临时文件不存在' };
            }
            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 保存临时文件为正式文件
     * @param tempId 临时文件ID
     */
    async saveTempFile(tempId: string): Promise<OperationResult<FileIndexItem>> {
        try {
            const content = await this.tempManager.getTempContent(tempId);
            if (content === null) {
                return { success: false, error: '临时文件不存在或已过期' };
            }

            const metadata = await this.tempManager.getMetadata();
            const tempInfo = metadata.find(t => t.id === tempId);
            if (!tempInfo) {
                return { success: false, error: '临时文件元数据不存在' };
            }

            // 创建正式文件
            const result = await this.createFile(tempInfo.targetName, content, tempInfo.parentId);
            if (result.success) {
                // 标记临时文件为已保存并删除
                await this.tempManager.markAsSaved(tempId);
                await this.tempManager.deleteTemp(tempId);
            }

            return result;
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 获取未保存的临时文件列表
     */
    async getUnsavedFiles(): Promise<OperationResult<TempFileInfo[]>> {
        try {
            const files = await this.tempManager.getUnsavedFiles();
            return { success: true, data: files };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 添加文件打开记录
     * @param fileId 文件ID
     */
    async addOpenedFile(fileId: string): Promise<OperationResult<void>> {
        try {
            const index = await this.getFileIndex();
            const file = index.find(item => item.id === fileId);
            if (!file) {
                return { success: false, error: '文件不存在' };
            }

            const now = Date.now();
            const record = this.openedFilesCache.get(fileId) || {
                fileId,
                title: file.title,
                isDirectory: file.isDirectory,
                firstOpenTime: now,
                lastOpenTime: now,
                openCount: 0
            };

            record.lastOpenTime = now;
            record.openCount++;
            this.openedFilesCache.set(fileId, record);

            // 更新目录缓存
            await this.updateDirectoryCache(file, true);

            await this.saveOpenedFiles();
            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 移除文件打开记录
     * @param fileId 文件ID
     */
    async removeOpenedFile(fileId: string): Promise<OperationResult<void>> {
        try {
            const index = await this.getFileIndex();
            const file = index.find(item => item.id === fileId);
            if (file) {
                // 更新目录缓存
                await this.updateDirectoryCache(file, false);
            }

            this.openedFilesCache.delete(fileId);
            await this.saveOpenedFiles();
            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 添加或移除文件打开记录
     * @param fileId 文件ID
     */
    async addOrRemoveOpenedFile(fileId: string): Promise<OperationResult<void>> {
        try {
            const index = await this.getFileIndex();
            const file = index.find(item => item.id === fileId);
            if (!file) {
                return { success: false, error: '文件不存在' };
            }

            if (this.openedFilesCache.has(fileId)) {
                await this.removeOpenedFile(fileId);
            } else {
                await this.addOpenedFile(fileId);
            }

            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 获取已打开的文件记录列表
     */
    getOpenedFiles(): OpenedFileRecord[] {
        return Array.from(this.openedFilesCache.values())
          .filter(item => !item.isDirectory);
    }

    /**
     * 获取已打开的文件目录id
     */
    getOpenedDirectoryIds(): string[] {
        return Array.from(this.openedFilesCache.values())
            .filter(item => item.isDirectory)
            .map(item => item.fileId);
    }

    /**
     * 获取已打开的文件id
     */
    getOpenedFileIds(): string[] {
        return Array.from(this.openedFilesCache.values())
            .filter(item => !item.isDirectory)
            .map(item => item.fileId);
    }

    /**
     * 检查文件是否已打开
     * @param fileId 文件ID
     */
    isFileOpened(fileId: string): boolean {
        return this.openedFilesCache.has(fileId);
    }

    /**
     * 获取已打开的所有目录的文件树
     * @returns 目录树结果
     */
    async getOpenedDirectoryTrees(): Promise<OperationResult<DirectoryTreeNode[]>> {
        try {
            const now = Date.now();
            const index = await this.getFileIndex();
            const openedFiles = Array.from(this.openedFilesCache.keys());
            const openedDirectories = index.filter(item =>
                item.isDirectory && openedFiles.includes(item.id)
            );

            const trees: DirectoryTreeNode[] = [];
            for (const dir of openedDirectories) {
                // 检查缓存
                const cachedData = this.openedDirectoryCache.get(dir.relativePath);
                if (cachedData && (now - cachedData.createTime) < this.DIRECTORY_CACHE_TTL) {
                    // 缓存有效，直接使用
                    trees.push(cachedData.treeNode);
                    // 更新访问时间
                    cachedData.lastAccessTime = now;
                    continue;
                }

                // 缓存不存在或已过期，重新构建目录树
                const result = await this.buildDirectoryTree(dir.relativePath, {
                    includeFiles: true,
                    recursive: true
                });

                if (result.success && result.data) {
                    trees.push(result.data);
                    // 更新缓存
                    this.openedDirectoryCache.set(dir.relativePath, {
                        path: dir.relativePath,
                        treeNode: result.data,
                        createTime: now,
                        lastAccessTime: now
                    });
                }
            }

            return { success: true, data: trees };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 获取文件空间中的所有文件目录树
     * @returns 根目录树结果
     */
    async getDirectoryTrees(): Promise<OperationResult<DirectoryTreeNode>> {
        try {
            const now = Date.now();

            // 检查根目录缓存
            const rootCacheData = this.openedDirectoryCache.get('');
            if (rootCacheData && (now - rootCacheData.createTime) < this.DIRECTORY_CACHE_TTL) {
                // 缓存有效，直接使用
                rootCacheData.lastAccessTime = now;
                return { success: true, data: rootCacheData.treeNode };
            }

            // 构建完整的目录树
            const result = await this.buildDirectoryTree('', {
                includeFiles: true,
                recursive: true
            });

            if (result.success && result.data) {
                // 更新根目录缓存
                this.openedDirectoryCache.set('', {
                    path: '',
                    treeNode: result.data,
                    createTime: now,
                    lastAccessTime: now
                });
            }

            return result;
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 懒加载指定目录的内容
     * @param directoryId 目录ID
     * @returns 目录树结果
     */
    async lazyLoadDirectoryTrees(directoryId: string): Promise<OperationResult<DirectoryTreeNode>> {
        try {
            // 获取目录信息
            const index = await this.getFileIndex();
            const directory = index.find(item =>
                item.isDirectory && item.id === directoryId
            );

            if (!directory) {
                return { success: false, error: '目录不存在' };
            }

            // 构建目录树（只包含直接子项）
            return await this.buildDirectoryTree(directory.relativePath, {
                includeFiles: true,
                recursive: false, // 不递归，只获取直接子项
                startFromPath: true // 从当前目录开始构建树
            });
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 获取根目录
     * @returns 根目录下
     */
    async getRootDirectory(): Promise<OperationResult<DirectoryTreeNode>> {
        try {
            const root = this.buildRootDirectory();

            // 获取文件索引
            const index = await this.getFileIndex();

            // 过滤出根目录下的直接子项
            const rootItems = index.filter(item => {
                // 根目录下的项目的相对路径中不应该包含分隔符
                return item.relativePath && !item.relativePath.includes(FileUtil.separator);
            });

            // 转换为目录树节点
            root.children = rootItems.map(item => ({
                id: item.id,
                item,
                children: [],
                level: 1,
                expanded: false
            }));

            return { success: true, data: root };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 遍历目录树
     * @param callback 遍历回调函数
     * @param startPath 起始路径（相对于文件空间根目录）
     * @param options 遍历选项
     */
    async walkDirectoryTree(
        callback: TreeWalkCallback,
        startPath = '',
        options: TreeWalkOptions = {}
    ): Promise<OperationResult<void>> {
        try {
            const treeResult = await this.buildDirectoryTree(startPath, options);
            if (!treeResult.success || !treeResult.data) {
                return { success: false, error: treeResult.error || '构建目录树失败' };
            }

            const walk = async (node: DirectoryTreeNode, parent?: DirectoryTreeNode) => {
                await callback(node, parent);
                if (node.children && (options.recursive || node.level === 0)) {
                    for (const child of node.children) {
                        await walk(child, node);
                    }
                }
            };

            await walk(treeResult.data);
            return { success: true };
        } catch (error) {
            return { success: false, error: String(error) };
        }
    }

    /**
     * 更新目录缓存中的文件或目录
     * @param file 文件或目录信息
     * @param isAdd 是否是添加操作
     */
    private async updateDirectoryCache(file: FileIndexItem, isAdd: boolean): Promise<void> {
        const now = Date.now();
        const pathParts = file.relativePath.split(FileUtil.separator);
        pathParts.pop(); // 移除文件名，获取父目录路径
        const parentPath = pathParts.join(FileUtil.separator);

        // 遍历所有缓存的目录
        for (const [cachePath, cacheData] of this.openedDirectoryCache) {
            // 如果文件在这个缓存的目录下
            if (file.relativePath.startsWith(cachePath)) {
                // 更新目录树
                const result = await this.buildDirectoryTree(cachePath, {
                    includeFiles: true,
                    recursive: true
                });

                if (result.success && result.data) {
                    this.openedDirectoryCache.set(cachePath, {
                        path: cachePath,
                        treeNode: result.data,
                        createTime: now,
                        lastAccessTime: now
                    });
                }
            }
        }
    }

    /**
     * 清除指定路径的目录缓存
     * @param path 目录路径
     */
    private clearDirectoryCache(path: string): void {
        this.openedDirectoryCache.delete(path);
    }

    /**
     * 清除所有目录缓存
     */
    private clearAllDirectoryCache(): void {
        this.openedDirectoryCache.clear();
    }
}
